/* Copyright(c) 2010- Siro-info Co.(http://www.siro-info.com)
 * All rights reserved.
 */
package com.siro.pm.utils;

import java.io.File;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import org.h2.tools.Server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.siro.pm.Constants;

/**
 * Class Declaration: <br/>
 * 
 * @version v1.0
 * @since HSQLDBService.java v1.0
 */
public class EmbededDb {
	private static final Logger logger = LoggerFactory
			.getLogger(EmbededDb.class);

	public static String DB_PATH = "db";
	public static String DB_NAME = "easypm";
	public static String DB_PORT = System
			.getProperty("embeded.db.port", "9092");
	public static final String driver = "org.h2.Driver";
	public static final String protocol = "jdbc:h2:";

	private Server server;
	private Connection conn;

	private static EmbededDb instance = new EmbededDb();

	private EmbededDb() {

	}

	public static EmbededDb getInstance() {
		return instance;
	}

	public void start() throws Exception {
		logger.info("开始连接到数据库   " + DB_NAME);
		server = Server.createTcpServer("-tcpPort", DB_PORT);
		server.start();
		Class.forName(driver);

		// 判断数据库是否已存在
		String dbPath = "file:./" + DB_PATH + File.separator + DB_NAME
				+ ".h2.db";
		URL url = new URL(dbPath);
		File file = new File(url.getFile());
		boolean needInit = false;
		if (!file.exists()) {
			needInit = true;
		}

		logger.info("Embeded Db Url:" + protocol + DB_PATH + File.separator
				+ DB_NAME + ";");
		conn = DriverManager.getConnection(protocol + DB_PATH + File.separator
				+ DB_NAME + ";", "sa", "");
		conn.setAutoCommit(true);
		logger.info("连接到数据库  " + DB_NAME);

		// 初始化数据库
		if (needInit) {
			DatabaseOperation.importSqlScript(
					conn,
					this.getClass().getClassLoader()
							.getResourceAsStream(Constants.DB_INIT_SCRIPT));
			logger.info("初始化数据库成功");
		}
	}

	/**
	 * In embedded mode, an application should shut down the database.
	 * 
	 */
	public void stopDb() {
		logger.info("开始停止数据库...");
		// 1. close the connection,shutdown the database
		try {
			conn.close();
			server.stop();
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		logger.info("数据库正常停止");
	}

	public Connection getConnection() throws Exception {
		Connection connection = DriverManager.getConnection(protocol + DB_PATH
				+ File.separator + DB_NAME + ";", "sa", "");
		return connection;
	}

	public static void main(String[] args) throws Exception {
		EmbededDb ds = new EmbededDb();
		try {
			ds.start();
			ds.getConnection();
		} catch (SQLException sqle) {
			sqle.printStackTrace();
		} finally {
			ds.stopDb();
		}
	}

}
